#!/bin/bash
#    Copyright 2015 Mirantis, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.


confdir="/etc/dockerctl"
. "$confdir/config"
. "/usr/share/dockerctl/functions"
DEBUG=true


#Sets var nonopts
declare -a nonopts
parse_options "$@"
set -- "${nonopts[@]}"

if [ -z "$1" ] || [ "$1" = "help" ]; then
  echo "Please specify a command."
  show_usage
  exit 1
fi

if [ -z "$2" ] || [ "$2" = "all" ]; then
  container="all"
else
  container=$2
fi

container_seq=$CONTAINER_SEQUENCE

if [ "$1" == "build" ]; then
  if [ "$container" = "storage" ]; then
    build_storage_containers
    run_storage_containers
  elif [ "$container" = "all" ];then
    #Step 1: prepare storage containers
    build_storage_containers
    run_storage_containers

    #Prepare iptables just in case ICC is broken
    allow_all_docker_traffic

    #Step 2: Launch all in order, checking each one
    for service in $container_seq; do
      start_container $service
      check_ready $service
    done
  else
    start_container $container
  fi
elif [ "$1" == "start" ]; then
  if [ "$container" = "all" ];then
    for service in $container_seq; do
      start_container $service
      check_ready $service
      sleep 4
    done
  else
    shift 2
    start_container $container $@
    if ! [[ "$@" =~ "--attach" ]]; then
      check_ready $container
    fi
  fi
elif [ "$1" == "check" ]; then
  if [ "$container" = "all" ];then
    exit_code=0
    for service in $container_seq; do
      check_ready $service || exit_code=1
    done
    exit $exit_code
  else
    check_ready $container
  fi
elif [ "$1" == "list" ]; then
  shift 1
  list_containers "$@"
elif [ "$1" == "copy" ]; then
  shift 1
  copy_files "$@"
elif [ "$1" == "restart" ]; then
  shift 2
  restart_container $container $@
elif [ "$1" == "stop" ]; then
  shift 2
  stop_container $container $@
elif [ "$1" == "revert" ]; then
  shift 2
  revert_container $container $@
elif [ "$1" == "shell" ]; then
  shift 2
  shell_container $container "$@"
elif [ "$1" == "upgrade" ]; then
  shift 2
  upgrade_container $container $@
elif [ "$1" == "restore" ]; then
  shift
  restore "$@"
elif [ "$1" == "backup" ]; then
  shift
  backup "$@"
elif [ "$1" == "destroy" ]; then
  shift 2
  destroy_container $container $@
elif [ "$1" == "logs" ]; then
  logs $container
elif [ "$1" == "post_start_hooks" ]; then
  shift 2
  post_start_hooks "$container" "$@"
else
  echo "Invalid selection."
  show_usage
fi
